from fastapi import APIRouter
from typing import List

from app.schemas.env_parameter import EnvParameterCreate, EnvParameterOut, EnvParameterDetailOut, CategoryOut, \
    CategorizedItems
from app.crud.env_parameter import (
    create_env_parameter,
    get_env_parameter_by_id,
    delete_env_parameter,
    list_env_parameters_grouped as list_env_parameters,
    get_all_categories_item
)
from app.utils.Result import Result

router = APIRouter()

@router.post("/", response_model=Result[bool], summary="新增环境参数配置")
async def create_env_parameter_api(data: EnvParameterCreate):
    try:
        success = await create_env_parameter(data)
        if not success:
            return Result.error(code=400, msg="参数配置校验失败或创建失败")
        return Result.ok(data=True, msg="创建成功")
    except ValueError as e:
        return Result.error(code=400, msg=str(e))
    except Exception as e:
        return Result.error(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/categories", response_model=Result[CategorizedItems], summary="获取所有环境参数类别")
async def get_all_categories_api():
    categories = await get_all_categories_item()
    return Result.ok(data=categories)


@router.get("/{env_param_id}", response_model=Result[EnvParameterDetailOut], summary="根据ID获取环境参数配置详情")
async def get_env_parameter_api(env_param_id: int):
    try:
        env_param = await get_env_parameter_by_id(env_param_id)
        if not env_param:
            return Result.error(code=404, msg="环境参数配置不存在")
        return Result.ok(data=env_param)
    except Exception as e:
        return Result.error(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/", response_model=Result[List[EnvParameterOut]], summary="获取所有环境参数配置列表")
async def list_env_parameters_api():
    env_params = await list_env_parameters()
    return Result.ok(data=env_params)

@router.delete("/{env_param_id}", response_model=Result[str], summary="根据ID删除环境参数配置")
async def delete_env_parameter_api(env_param_id: int):
    deleted_count = await delete_env_parameter(env_param_id)
    if deleted_count == 0:
        return Result.error(code=404, msg="删除失败，配置不存在")
    return Result.ok(msg="删除成功")


